﻿using System;
using System.Reflection;
using DevExpress.XtraBars;
using Moonlite.ExtensionApi.XimlInterfaces;

namespace Moonlite.Platform.Ximl {
    public static class XimlEventHandler {
        internal static void OnButtonClicked(object sender, ItemClickEventArgs e) {
            const string CommandInterfaceName = "ICommand";
            BarItemDescriptor descriptor = (BarItemDescriptor)e.Item.Tag;
            if (descriptor != null && descriptor.CommandType != null) {
                bool inheritsInterface = false;
                foreach (Type interfaceType in descriptor.CommandType.GetInterfaces()) {
                    if (interfaceType.Name == CommandInterfaceName) {
                        inheritsInterface = true;
                        break;
                    }
                }
                if (!inheritsInterface) {
                    throw new TargetException("The Command class must inherit Moonlite.Platform.Ximl.ICommand.");
                }
                object commandObject = Activator.CreateInstance(descriptor.CommandType);
                MethodInfo info = descriptor.CommandType.GetMethod("Run");
                if (info != null) {
                    info.Invoke(commandObject, new object[] { descriptor });
                }
            }
        }
    }
}
